package top.dj.jdbc.routing.component;

import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import top.dj.jdbc.routing.ClientDataSource;
import top.dj.jdbc.routing.ClientDataSourceContextHolder;

import java.util.Objects;

/**
 * {@link javax.sql.DataSource} for spring framework that will gives the desired
 * datasource based on the
 * current value stored in the {@link ClientDataSourceContextHolder}
 *
 * @Author: DengJia
 * @Date: 2021/9/26 22:31
 * @Description: 重写 determineCurrentLookupKey 方法,
 * 返回所使用的数据源的 Key(master/slave) 给到 resolvedDataSources,
 * 从而通过 Key 从 resolvedDataSources 里拿到其对应的 DataSource.
 */

@Slf4j
public class ClientDataSourceRouter extends AbstractRoutingDataSource {

    @Override
    protected Object determineCurrentLookupKey() {
        ClientDataSource clientDataSource = ClientDataSourceContextHolder.getClientDatabase();
        if (Objects.isNull(clientDataSource)) {
            log.debug("null client database, use default {}", ClientDataSource.MASTER);
            clientDataSource = ClientDataSource.MASTER;
        }
        log.trace("use {} as database", clientDataSource);
        return clientDataSource;
    }

}
